<template>
  <view class="promotion-edit-container">
    <view class="page-header">
      <text class="page-title">编辑促销活动</text>
      <text class="page-subtitle">{{ stepTitles[currentStep - 1] }}</text>
    </view>

    <!-- 加载状态 -->
    <view v-if="pageLoading" class="page-loading-container">
      <view class="loading-spinner"></view>
      <text class="loading-text">加载数据中...</text>
    </view>

    <!-- 步骤指示器 -->
    <view v-else class="steps-indicator">
      <view v-for="(step, index) in steps" :key="index" class="step-item" :class="{ active: currentStep === index + 1, completed: currentStep > index + 1 }">
        <view class="step-number">{{ index + 1 }}</view>
        <text class="step-label">{{ step }}</text>
      </view>
    </view>

    <view class="form-container">
      <!-- 步骤1: 基本信息 -->
      <view v-if="currentStep === 1" class="form-step">
        <view class="form-section">
          <text class="section-title">基本信息</text>
          
      <view class="form-item">
            <text class="form-label required">活动标题</text>
            <uni-easyinput 
              v-model="formData.title"
              placeholder="请输入促销活动标题"
              :maxlength="100"
              :clearable="true"
              trim="all"
            />
        <text v-if="errors.title" class="error-text">{{ errors.title }}</text>
      </view>

      <view class="form-item">
            <text class="form-label">活动描述</text>
            <textarea 
              v-model="formData.description" 
              class="form-textarea" 
              placeholder="请输入活动简短描述（显示在列表中）"
              maxlength="200"
            />
      </view>

      <view class="form-item">
            <text class="form-label">活动图片</text>
            <uni-file-picker 
              v-model="imageFileList"
              file-mediatype="image"
              mode="grid"
              :limit="1"
              :auto-upload="false"
              @select="handleImageSelect"
              @delete="handleImageDelete"
            />
            <text class="form-hint">建议尺寸：750x400像素，支持jpg、png格式，最大5MB（提交时上传）</text>
      </view>

      <view class="form-item">
            <text class="form-label">活动详细内容</text>
            
            <!-- H5端专业工具栏 -->
            <!-- #ifdef H5 -->
            <view class="professional-editor-container">
              <view class="professional-toolbar">
                <!-- 第一行工具栏 -->
                <view class="toolbar-row">
                  <!-- 撤销/重做 -->
                  <button class="pro-btn icon-btn" @click="editorUndo" title="撤销">
                    <text class="pro-icon">↶</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="editorRedo" title="重做">
                    <text class="pro-icon">↷</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 文本格式 -->
                  <button class="pro-btn icon-btn" @click="formatBold" title="粗体">
                    <text class="pro-icon bold">B</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatItalic" title="斜体">
                    <text class="pro-icon italic">I</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatUnderline" title="下划线">
                    <text class="pro-icon underline">U</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatStrike" title="删除线">
                    <text class="pro-icon strike">S</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 标题 -->
                  <button class="pro-btn icon-btn" @click="formatHeader('H1')" title="一级标题">
                    <text class="pro-icon">H₁</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatHeader('H2')" title="二级标题">
                    <text class="pro-icon">H₂</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatHeader('H3')" title="三级标题">
                    <text class="pro-icon">H₃</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 列表 -->
                  <button class="pro-btn icon-btn" @click="formatList('bullet')" title="无序列表">
                    <text class="pro-icon">•••</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatList('ordered')" title="有序列表">
                    <text class="pro-icon">123</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatList('check')" title="任务列表">
                    <text class="pro-icon">☑</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 对齐方式 -->
                  <button class="pro-btn icon-btn" @click="formatAlign('left')" title="左对齐">
                    <text class="pro-icon">≡</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatAlign('center')" title="居中对齐">
                    <text class="pro-icon">≣</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatAlign('right')" title="右对齐">
                    <text class="pro-icon">≡</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 缩进 -->
                  <button class="pro-btn icon-btn" @click="formatIndent('-1')" title="减少缩进">
                    <text class="pro-icon">⇤</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="formatIndent('+1')" title="增加缩进">
                    <text class="pro-icon">⇥</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 插入 -->
                  <button class="pro-btn icon-btn" @click="insertDivider" title="插入分割线">
                    <text class="pro-icon">─</text>
                  </button>
                  <button class="pro-btn icon-btn" @click="insertImage" title="插入图片">
                    <text class="pro-icon">🖼</text>
                  </button>
                  
                  <view class="pro-divider"></view>
                  
                  <!-- 清除 -->
                  <button class="pro-btn icon-btn danger-btn" @click="clearFormat" title="清除格式">
                    <text class="pro-icon">⌧</text>
                  </button>
                </view>
              </view>
              
              <view class="professional-editor-wrapper">
                <editor 
                  id="promotion-editor"
                  class="professional-rich-editor"
                  :placeholder="'请输入活动详细内容...'"
                  @ready="onEditorReady"
                  @input="onEditorInput"
                  :show-img-size="true"
                  :show-img-toolbar="true"
                  :show-img-resize="true"
                />
              </view>
            </view>
            <!-- #endif -->
            
            <!-- 小程序端紧凑工具栏 -->
            <!-- #ifndef H5 -->
            <view class="compact-editor-container">
              <!-- 第一行 -->
              <view class="compact-toolbar">
                <button class="compact-btn" @click="editorUndo">
                  <text class="compact-icon">↶</text>
                </button>
                <button class="compact-btn" @click="formatBold">
                  <text class="compact-icon bold">B</text>
                </button>
                <button class="compact-btn" @click="formatItalic">
                  <text class="compact-icon italic">I</text>
                </button>
                <button class="compact-btn" @click="formatUnderline">
                  <text class="compact-icon underline">U</text>
                </button>
                <button class="compact-btn" @click="formatStrike">
                  <text class="compact-icon strike">S</text>
                </button>
                <button class="compact-btn" @click="formatHeader('H2')">
                  <text class="compact-icon">H</text>
                </button>
                <button class="compact-btn danger" @click="clearFormat">
                  <text class="compact-icon">✕</text>
                </button>
              </view>
              
              <!-- 第二行 -->
              <view class="compact-toolbar">
                <button class="compact-btn" @click="formatList('bullet')">
                  <text class="compact-icon">•</text>
                </button>
                <button class="compact-btn" @click="formatList('ordered')">
                  <text class="compact-icon">123</text>
                </button>
                <button class="compact-btn" @click="formatAlign('left')">
                  <text class="compact-icon">≡</text>
                </button>
                <button class="compact-btn" @click="formatAlign('center')">
                  <text class="compact-icon">≣</text>
                </button>
                <button class="compact-btn" @click="formatIndent('-1')">
                  <text class="compact-icon">⇤</text>
                </button>
                <button class="compact-btn" @click="formatIndent('+1')">
                  <text class="compact-icon">⇥</text>
                </button>
                <button class="compact-btn" @click="insertImage">
                  <text class="compact-icon">📷</text>
                </button>
              </view>
              
              <view class="compact-editor-wrapper">
                <editor 
                  id="promotion-editor"
                  class="compact-rich-editor"
                  :placeholder="'请输入活动详细内容...'"
                  @ready="onEditorReady"
                  @input="onEditorInput"
                  :show-img-size="true"
                  :show-img-toolbar="true"
                  :show-img-resize="true"
                />
              </view>
            </view>
            <!-- #endif -->
            
            <text class="form-hint">💡 使用工具栏格式化文本，可添加标题、列表、图片等丰富内容</text>
          </view>
        </view>
      </view>

      <!-- 步骤2: 促销配置 -->
      <view v-if="currentStep === 2" class="form-step">
        <view class="form-section">
          <text class="section-title">促销类别</text>
          
          <view class="form-item">
            <text class="form-label required">促销类别</text>
            <radio-group @change="onPromotionCategoryChange" class="radio-group vertical">
              <label class="radio-label-block" v-for="cat in promotionCategories" :key="cat.value">
                <radio :value="cat.value.toString()" :checked="formData.promotion_category === cat.value" />
                <view class="radio-content">
                  <text class="radio-title">{{ cat.label }}</text>
                  <text class="radio-desc">{{ cat.desc }}</text>
                </view>
              </label>
            </radio-group>
            <text v-if="errors.promotion_category" class="error-text">{{ errors.promotion_category }}</text>
          </view>
        </view>

        <view class="form-section">
          <text class="section-title">用户标签（适用用户）</text>
          
          <view class="form-item">
            <text class="form-label">选择用户标签</text>
            <checkbox-group @change="onUserTagsChange" class="checkbox-group">
              <label class="checkbox-label" v-for="tag in userTagOptions" :key="tag.value">
                <checkbox :value="tag.value" :checked="formData.user_tags.includes(tag.value)" />
                <text>{{ tag.label }}</text>
              </label>
            </checkbox-group>
            <text class="form-hint">不选择表示所有用户均可参与</text>
          </view>
        </view>

        <view class="form-section">
          <text class="section-title">适用范围</text>

      <view class="form-item">
            <text class="form-label">适用范围</text>
            <radio-group @change="onApplyScopeChange" class="radio-group">
              <label class="radio-label">
                <radio value="1" :checked="formData.apply_scope === 1" />
                <text>指定商品/服务</text>
              </label>
              <label class="radio-label">
                <radio value="2" :checked="formData.apply_scope === 2" />
                <text>指定类别</text>
              </label>
              <label class="radio-label">
                <radio value="3" :checked="formData.apply_scope === 3" />
                <text>全场通用</text>
              </label>
            </radio-group>
          </view>

          <view v-if="formData.apply_scope !== 3" class="form-item">
            <text class="form-label">目标类型</text>
            <radio-group @change="onTargetTypeChange" class="radio-group">
              <label class="radio-label">
                <radio value="1" :checked="formData.apply_target_type === 1" />
                <text>服务</text>
              </label>
              <label class="radio-label">
                <radio value="2" :checked="formData.apply_target_type === 2" />
                <text>产品</text>
              </label>
              <label class="radio-label">
                <radio value="3" :checked="formData.apply_target_type === 3" />
                <text>全部</text>
              </label>
            </radio-group>
          </view>

          <view v-if="formData.apply_scope === 1" class="form-item">
            <text class="form-label">指定商品/服务</text>
            <button class="select-btn" @click="showProductServicePicker">
              <text class="select-btn-text">选择商品/服务</text>
              <text class="select-btn-icon">+</text>
            </button>
            
            <!-- 已选择的商品/服务列表 -->
            <view v-if="selectedItems.length > 0" class="selected-items-list">
              <view v-for="(item, index) in selectedItems" :key="item._id" class="selected-item-card">
                <view class="item-info">
                  <text class="item-name">{{ item.name }}</text>
                  <text class="item-price">¥{{ item.price }}</text>
                </view>
                <button class="remove-btn" @click="removeSelectedItem(index)">×</button>
              </view>
            </view>
            <text v-else class="form-hint">暂未选择商品/服务</text>
          </view>

          <view v-if="formData.apply_scope === 2" class="form-item">
            <text class="form-label">选择类别</text>
            <checkbox-group @change="onCategoriesChange" class="checkbox-group">
              <label class="checkbox-label" v-for="cat in categoryOptions" :key="cat.value">
                <checkbox :value="cat.value" :checked="formData.apply_categories.includes(cat.value)" />
                <text>{{ cat.label }}</text>
              </label>
            </checkbox-group>
          </view>
        </view>
      </view>

      <!-- 步骤3: 优惠规则 -->
      <view v-if="currentStep === 3" class="form-step">
        <view class="form-section">
          <text class="section-title">折扣类型</text>
          
          <view class="form-item">
            <text class="form-label required">折扣类型</text>
            <radio-group @change="onDiscountTypeChange" class="radio-group vertical">
              <label class="radio-label-block" v-for="type in discountTypes" :key="type.value">
                <radio :value="type.value.toString()" :checked="formData.discount_type === type.value" />
                <view class="radio-content">
                  <text class="radio-title">{{ type.label }}</text>
                  <text class="radio-desc">{{ type.desc }}</text>
                </view>
              </label>
            </radio-group>
            <text v-if="errors.discount_type" class="error-text">{{ errors.discount_type }}</text>
          </view>
        </view>

        <view class="form-section">
          <text class="section-title">优惠配置</text>
          
          <!-- 百分比折扣 -->
          <view v-if="formData.discount_type === 1" class="form-item">
            <text class="form-label required">折扣值</text>
            <uni-easyinput 
              v-model="formData.discount_value" 
              type="number" 
              placeholder="例如：0.8表示8折"
              :clearable="true"
              trim="all"
            />
            <text class="form-hint">输入0-1之间的数值，例如0.8表示8折</text>
            <text v-if="errors.discount_value" class="error-text">{{ errors.discount_value }}</text>
          </view>

          <!-- 固定金额减免 -->
          <view v-if="formData.discount_type === 2" class="form-item">
            <text class="form-label required">减免金额（元）</text>
            <uni-easyinput 
              v-model="formData.discount_value" 
              type="number" 
              placeholder="例如：50"
              :clearable="true"
              trim="all"
            />
            <text class="form-hint">直接减免的金额</text>
            <text v-if="errors.discount_value" class="error-text">{{ errors.discount_value }}</text>
          </view>

          <!-- 满减优惠 -->
          <view v-if="formData.discount_type === 3">
            <view class="form-item">
              <text class="form-label required">最低消费金额（元）</text>
              <uni-easyinput 
                v-model="formData.min_amount" 
                type="number" 
                placeholder="例如：300"
                :clearable="true"
                trim="all"
              />
              <text v-if="errors.min_amount" class="error-text">{{ errors.min_amount }}</text>
            </view>
            <view class="form-item">
              <text class="form-label required">减免金额（元）</text>
              <uni-easyinput 
                v-model="formData.discount_value" 
                type="number" 
                placeholder="例如：50"
                :clearable="true"
                trim="all"
              />
              <text class="form-hint">满足最低消费后减免的金额</text>
              <text v-if="errors.discount_value" class="error-text">{{ errors.discount_value }}</text>
            </view>
          </view>

          <!-- 特价 -->
          <view v-if="formData.discount_type === 4" class="form-item">
            <text class="form-label required">特价金额（元）</text>
            <uni-easyinput 
              v-model="formData.special_price" 
              type="number" 
              placeholder="例如：199"
              :clearable="true"
              trim="all"
            />
            <text class="form-hint">商品/服务的特价金额</text>
            <text v-if="errors.special_price" class="error-text">{{ errors.special_price }}</text>
      </view>

      <view class="form-item">
            <text class="form-label">最大优惠金额（元）</text>
            <uni-easyinput 
              v-model="formData.max_discount_amount" 
              type="number" 
              placeholder="优惠封顶金额，不填表示无上限"
              :clearable="true"
              trim="all"
            />
            <text class="form-hint">优惠金额的上限，防止过度优惠</text>
          </view>
        </view>
      </view>

      <!-- 步骤4: VIP奖励（可选）-->
      <view v-if="currentStep === 4" class="form-step">
        <view class="form-section">
          <text class="section-title">VIP奖励配置</text>
          <text class="section-desc">可选功能，用于设置充值/消费达标后自动晋升VIP</text>
          
          <view class="form-item">
            <text class="form-label">VIP奖励类型</text>
            <radio-group @change="onVipRewardTypeChange" class="radio-group">
              <label class="radio-label">
                <radio value="0" :checked="formData.vip_reward_type === 0" />
                <text>不设置</text>
              </label>
              <label class="radio-label">
                <radio value="1" :checked="formData.vip_reward_type === 1" />
                <text>充值获得VIP</text>
              </label>
              <label class="radio-label">
                <radio value="2" :checked="formData.vip_reward_type === 2" />
                <text>消费晋升VIP</text>
              </label>
            </radio-group>
          </view>

          <view v-if="formData.vip_reward_type > 0">
            <view class="form-item">
              <text class="form-label required">充值/消费阈值（元）</text>
              <uni-easyinput 
                v-model="formData.vip_reward_threshold" 
                type="number" 
                placeholder="达到此金额可获得VIP"
                :clearable="true"
                trim="all"
              />
              <text v-if="errors.vip_reward_threshold" class="error-text">{{ errors.vip_reward_threshold }}</text>
      </view>

      <view class="form-item">
              <text class="form-label required">VIP等级</text>
              <radio-group @change="onVipRewardLevelChange" class="radio-group">
                <label class="radio-label">
                  <radio value="1" :checked="formData.vip_reward_level === 1" />
                  <text>VIP1</text>
                </label>
                <label class="radio-label">
                  <radio value="2" :checked="formData.vip_reward_level === 2" />
                  <text>VIP2</text>
                </label>
                <label class="radio-label">
                  <radio value="3" :checked="formData.vip_reward_level === 3" />
                  <text>VIP3</text>
                </label>
              </radio-group>
              <text v-if="errors.vip_reward_level" class="error-text">{{ errors.vip_reward_level }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 步骤5: 其他设置 -->
      <view v-if="currentStep === 5" class="form-step">
        <view class="form-section">
          <text class="section-title">时间设置</text>
          
          <view class="form-item">
            <text class="form-label required">活动开始日期</text>
            <picker mode="date" :value="formData.start_date" @change="onStartDateChange" class="date-picker">
              <view class="picker-input">
                {{ formData.start_date || '请选择开始日期' }}
              </view>
            </picker>
        <text v-if="errors.start_date" class="error-text">{{ errors.start_date }}</text>
      </view>

      <view class="form-item">
            <text class="form-label required">活动结束日期</text>
            <picker mode="date" :value="formData.end_date" @change="onEndDateChange" class="date-picker">
              <view class="picker-input">
                {{ formData.end_date || '请选择结束日期' }}
              </view>
            </picker>
        <text v-if="errors.end_date" class="error-text">{{ errors.end_date }}</text>
          </view>
      </view>

        <view class="form-section">
          <text class="section-title">优先级和排序</text>

      <view class="form-item">
            <text class="form-label">优先级</text>
            <uni-easyinput 
              v-model="formData.priority" 
              type="number" 
              placeholder="数字越大优先级越高，默认为5"
              :clearable="true"
              trim="all"
            />
            <text class="form-hint">当多个促销同时适用时，优先级高的生效</text>
          </view>

          <view class="form-item">
            <text class="form-label">显示顺序</text>
            <uni-easyinput 
              v-model="formData.display_order" 
              type="number" 
              placeholder="列表中的显示顺序，默认为100"
              :clearable="true"
              trim="all"
            />
          </view>
        </view>

        <view class="form-section">
          <text class="section-title">状态</text>

      <view class="form-item">
            <text class="form-label">活动状态</text>
        <radio-group @change="onStatusChange" class="radio-group">
          <label class="radio-label">
            <radio value="1" :checked="formData.status === 1" />
            <text>启用</text>
          </label>
          <label class="radio-label">
                <radio value="2" :checked="formData.status === 2" />
                <text>停用</text>
          </label>
        </radio-group>
          </view>
        </view>
      </view>

      <!-- 按钮组 -->
      <view class="form-actions">
        <button v-if="currentStep > 1" class="btn-prev" @click="handlePrevStep">上一步</button>
        <button v-if="currentStep < 5" class="btn-next" @click="handleNextStep">下一步</button>
        <button v-if="currentStep === 5" class="btn-submit" @click="handleSubmit">提交创建</button>
        <button class="btn-cancel" @click="handleCancel">取消</button>
      </view>
    </view>

    <!-- 商品/服务选择器弹窗 -->
    <view v-if="showPicker" class="picker-modal" @click="closePicker">
      <view class="picker-content" @click.stop>
        <view class="picker-header">
          <text class="picker-title">选择商品/服务</text>
          <button class="picker-close" @click="closePicker">×</button>
        </view>
        
        <!-- 搜索框 -->
        <view class="picker-search">
          <input 
            v-model="searchKeyword" 
            class="search-input" 
            placeholder="搜索商品/服务名称" 
            @input="handleSearch"
          />
        </view>

        <!-- 目标类型切换 -->
        <view class="picker-tabs">
          <button 
            class="tab-btn" 
            :class="{ active: pickerTargetType === 1 }" 
            @click="switchPickerType(1)"
          >
            服务
          </button>
          <button 
            class="tab-btn" 
            :class="{ active: pickerTargetType === 2 }" 
            @click="switchPickerType(2)"
          >
            产品
          </button>
        </view>
        
        <!-- 商品/服务列表 -->
        <scroll-view class="picker-list" scroll-y>
          <view v-if="filteredPickerItems.length === 0" class="empty-tip">
            <text>暂无数据</text>
          </view>
          <view 
            v-for="item in filteredPickerItems" 
            :key="item._id" 
            class="picker-item"
            @click="toggleItemSelection(item._id)"
          >
            <checkbox 
              :value="item._id" 
              :checked="isItemSelected(item._id)"
            />
            <view class="picker-item-info">
              <text class="picker-item-name">{{ item.name }}</text>
              <text class="picker-item-desc">{{ item.description || '暂无描述' }}</text>
              <text class="picker-item-price">¥{{ item.price }}</text>
            </view>
          </view>
        </scroll-view>
        
        <!-- 底部操作按钮 -->
        <view class="picker-footer">
          <button class="picker-btn-cancel" @click="closePicker">取消</button>
          <button class="picker-btn-confirm" @click="confirmSelection">
            确定 (已选{{ tempSelectedIds.length }}项)
          </button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'

const dhPromotions = uniCloud.importObject('dh-hospital_promotions')
const db = uniCloud.database()

const pageLoading = ref(true)
const promotionId = ref('')
const currentStep = ref(1)
const editorCtx = ref(null)
const imageFileList = ref([])
const originalImageUrl = ref('') // 存储原始图片URL
const steps = ['基本信息', '促销配置', '优惠规则', 'VIP奖励', '其他设置']
const stepTitles = [
  '填写活动基本信息',
  '配置促销类别和适用范围',
  '设置优惠规则',
  '配置VIP奖励（可选）',
  '完成其他设置'
]

// 商品/服务选择器相关
const showPicker = ref(false)
const pickerTargetType = ref(1) // 1=服务, 2=产品
const searchKeyword = ref('')
const allPickerItems = ref([]) // 所有商品/服务
const selectedItems = ref([]) // 已选择的商品/服务完整信息
const tempSelectedIds = ref([]) // 临时选择的ID列表（用于弹窗确认前）

const formData = reactive({
  title: '',
  description: '',
  image: '',
  content: '',
  promotion_category: 1,
  user_tags: [],
  apply_scope: 3,
  apply_target_type: 3,
  apply_target_ids: [],
  apply_categories: [],
  discount_type: 1,
  discount_value: '',
  min_amount: 0,
  max_discount_amount: null,
  special_price: null,
  vip_reward_type: 0,
  vip_reward_threshold: 0,
  vip_reward_level: 0,
  start_date: '',
  end_date: '',
  priority: 5,
  display_order: 100,
  status: 1,
  view_count: 0,
  use_count: 0
})

// 计算属性：根据搜索关键词和类型过滤商品/服务列表
const filteredPickerItems = computed(() => {
  let items = allPickerItems.value.filter(item => {
    // 根据目标类型过滤
    if (pickerTargetType.value === 1 && item.type !== 'service') return false
    if (pickerTargetType.value === 2 && item.type !== 'product') return false
    return true
  })
  
  // 根据搜索关键词过滤
  if (searchKeyword.value.trim()) {
    const keyword = searchKeyword.value.trim().toLowerCase()
    items = items.filter(item => 
      item.name.toLowerCase().includes(keyword) ||
      (item.description && item.description.toLowerCase().includes(keyword))
    )
  }
  
  return items
})

const errors = reactive({
  title: '',
  promotion_category: '',
  discount_type: '',
  discount_value: '',
  min_amount: '',
  special_price: '',
  vip_reward_threshold: '',
  vip_reward_level: '',
  start_date: '',
  end_date: ''
})

// ==================== 生命周期 ====================
onMounted(async () => {
  const pages = getCurrentPages()
  const currentPage = pages[pages.length - 1]
  promotionId.value = currentPage.options.id || ''
  
  if (!promotionId.value) {
    uni.showToast({
      title: '缺少促销活动ID',
      icon: 'none'
    })
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/business/hospital_promotions/list'
      })
    }, 1500)
    return
  }
  
  // 加载促销数据
  await loadPromotionData()
  
  // 加载商品/服务数据
  await loadProductServiceData()
  
  pageLoading.value = false
})

/**
 * 加载促销活动数据
 */
async function loadPromotionData() {
  try {
    const res = await dhPromotions.getPromotionById(promotionId.value)
    
    if (res.code === 200 && res.data) {
      const data = res.data
      
      // 填充表单数据
      Object.assign(formData, {
        title: data.title || '',
        description: data.description || '',
        image: data.image || '',
        content: data.content || '',
        promotion_category: data.promotion_category || 1,
        user_tags: data.user_tags || [],
        apply_scope: data.apply_scope || 3,
        apply_target_type: data.apply_target_type || 3,
        apply_target_ids: data.apply_target_ids || [],
        apply_categories: data.apply_categories || [],
        discount_type: data.discount_type || 1,
        discount_value: data.discount_value || '',
        min_amount: data.min_amount || 0,
        max_discount_amount: data.max_discount_amount || null,
        special_price: data.special_price || null,
        vip_reward_type: data.vip_reward_type || 0,
        vip_reward_threshold: data.vip_reward_threshold || 0,
        vip_reward_level: data.vip_reward_level || 0,
        start_date: data.start_date || '',
        end_date: data.end_date || '',
        priority: data.priority || 5,
        display_order: data.display_order || 100,
        status: data.status || 1
      })
      
      // 如果有图片，设置到imageFileList供uni-file-picker显示
      if (data.image) {
        originalImageUrl.value = data.image
        imageFileList.value = [{
          url: data.image,
          name: '活动图片'
        }]
      }
      
      // 如果有富文本内容，等编辑器准备好后设置
      if (data.content && editorReady.value) {
        try {
          editorCtx.value.setContents({
            html: data.content
          })
        } catch (err) {
          console.error('设置编辑器内容失败:', err)
        }
      }
      
      // 如果有指定商品/服务，需要加载它们的详细信息
      if (data.apply_target_ids && data.apply_target_ids.length > 0) {
        await loadSelectedItems(data.apply_target_ids)
      }
    } else {
      throw new Error(res.message || '加载失败')
    }
  } catch (err) {
    console.error('加载促销数据失败:', err)
    uni.showToast({
      title: err.message || '加载失败',
      icon: 'none'
    })
    setTimeout(() => {
      uni.redirectTo({
        url: '/pages/business/hospital_promotions/list'
      })
    }, 1500)
  }
}

/**
 * 加载已选择的商品/服务详情
 */
async function loadSelectedItems(ids) {
  try {
    const items = []
    
    // 查询服务
    const servicesRes = await db.collection('dh-services')
      .where({
        _id: db.command.in(ids)
      })
      .field({
        _id: true,
        service_name: true,
        base_price: true
      })
      .get()
    
    const servicesData = servicesRes.result?.data || servicesRes.data || []
    servicesData.forEach(service => {
      items.push({
        _id: service._id,
        name: service.service_name,
        price: service.base_price,
        type: 'service'
      })
    })
    
    // 查询商品
    const productsRes = await db.collection('dh-products')
      .where({
        _id: db.command.in(ids)
      })
      .field({
        _id: true,
        product_name: true,
        price: true
      })
      .get()
    
    const productsData = productsRes.result?.data || productsRes.data || []
    productsData.forEach(product => {
      items.push({
        _id: product._id,
        name: product.product_name,
        price: product.price,
        type: 'product'
      })
    })
    
    selectedItems.value = items
  } catch (err) {
    console.error('加载已选商品/服务失败:', err)
  }
}

const promotionCategories = [
  { value: 1, label: '用户标签促销', desc: '针对特定用户群体（新用户、VIP、生日用户等）' },
  { value: 2, label: '商品/服务促销', desc: '针对特定商品或服务的优惠' },
  { value: 3, label: 'VIP充值/消费促销', desc: '充值或消费达标晋升VIP' },
  { value: 4, label: '全场促销', desc: '全场通用的优惠活动' }
]

const userTagOptions = [
  { value: 'new_user', label: '新用户' },
  { value: 'vip1', label: 'VIP1会员' },
  { value: 'vip2', label: 'VIP2会员' },
  { value: 'vip3', label: 'VIP3会员' },
  { value: 'birthday', label: '生日用户' }
]

const categoryOptions = [
  { value: 'anti_inflammatory', label: '抗炎类' },
  { value: 'cleaning', label: '清洁类' },
  { value: 'treatment', label: '治疗类' },
  { value: 'cosmetic', label: '美容类' }
]

const discountTypes = [
  { value: 1, label: '百分比折扣', desc: '如：8折、9折' },
  { value: 2, label: '固定金额减免', desc: '如：减50元' },
  { value: 3, label: '满减优惠', desc: '如：满300减50' },
  { value: 4, label: '特价', desc: '如：特价199元' }
]

function onPromotionCategoryChange(e) {
  formData.promotion_category = parseInt(e.detail.value)
}

function onUserTagsChange(e) {
  formData.user_tags = e.detail.value
}

function onApplyScopeChange(e) {
  formData.apply_scope = parseInt(e.detail.value)
  if (formData.apply_scope === 3) {
    formData.apply_target_ids = []
    formData.apply_categories = []
  }
}

function onTargetTypeChange(e) {
  formData.apply_target_type = parseInt(e.detail.value)
}

function onCategoriesChange(e) {
  formData.apply_categories = e.detail.value
}

// 商品/服务选择器相关方法
async function showProductServicePicker() {
  showPicker.value = true
  pickerTargetType.value = formData.apply_target_type === 2 ? 2 : 1
  
  // 初始化临时选择列表为当前已选择的ID
  tempSelectedIds.value = [...formData.apply_target_ids]
  
  // 如果还没有加载数据，则加载
  if (allPickerItems.value.length === 0) {
    await loadProductServiceData()
  }
}

async function loadProductServiceData() {
  try {
    uni.showLoading({ title: '加载中...' })
    
    // 加载服务数据
    const servicesRes = await db.collection('dh-services')
      .where({
        status: 1
      })
      .field({
        _id: true,
        service_name: true,
        description: true,
        base_price: true
      })
      .get()
    
    // 加载产品数据
    const productsRes = await db.collection('dh-products')
      .where({
        status: 1
      })
      .field({
        _id: true,
        product_name: true,
        description: true,
        price: true
      })
      .get()
    
    // 提取数据（兼容多种返回格式）
    const servicesData = servicesRes.result?.data || servicesRes.data || []
    const productsData = productsRes.result?.data || productsRes.data || []
    
    // 合并数据并统一格式
    const services = servicesData.map(item => ({
      _id: item._id,
      name: item.service_name,
      description: item.description || '',
      price: item.base_price || 0,
      type: 'service'
    }))
    
    const products = productsData.map(item => ({
      _id: item._id,
      name: item.product_name,
      description: item.description || '',
      price: item.price || 0,
      type: 'product'
    }))
    
    allPickerItems.value = [...services, ...products]
    
    uni.hideLoading()
    
    if (allPickerItems.value.length === 0) {
      uni.showToast({ 
        title: '暂无商品/服务数据', 
        icon: 'none',
        duration: 2000
      })
    }
  } catch (err) {
    console.error('加载商品/服务数据失败:', err)
    uni.hideLoading()
    uni.showToast({ 
      title: '加载失败：' + (err.message || '未知错误'), 
      icon: 'none',
      duration: 3000
    })
  }
}

function switchPickerType(type) {
  pickerTargetType.value = type
  searchKeyword.value = ''
}

function handleSearch() {
  // 搜索关键词变化时，filteredPickerItems会自动更新
}

// 切换项目的选择状态（通过点击整行）
function toggleItemSelection(itemId) {
  const index = tempSelectedIds.value.indexOf(itemId)
  
  if (index > -1) {
    // 已选中，则取消选择
    tempSelectedIds.value.splice(index, 1)
  } else {
    // 未选中，则添加
    tempSelectedIds.value.push(itemId)
  }
}

function isItemSelected(itemId) {
  return tempSelectedIds.value.includes(itemId)
}

function confirmSelection() {
  // 保存选择的ID到formData
  formData.apply_target_ids = [...tempSelectedIds.value]
  
  // 更新已选择的商品/服务完整信息
  selectedItems.value = allPickerItems.value.filter(item => 
    formData.apply_target_ids.includes(item._id)
  )
  
  closePicker()
  
  uni.showToast({ 
    title: `已选择${selectedItems.value.length}项`, 
    icon: 'success' 
  })
}

function closePicker() {
  showPicker.value = false
  searchKeyword.value = ''
}

function removeSelectedItem(index) {
  const removedId = selectedItems.value[index]._id
  selectedItems.value.splice(index, 1)
  formData.apply_target_ids = formData.apply_target_ids.filter(id => id !== removedId)
}

function onDiscountTypeChange(e) {
  formData.discount_type = parseInt(e.detail.value)
  // 清空不相关的字段
  if (formData.discount_type !== 3) {
    formData.min_amount = 0
  }
  if (formData.discount_type !== 4) {
    formData.special_price = null
  }
}

function onVipRewardTypeChange(e) {
  formData.vip_reward_type = parseInt(e.detail.value)
  if (formData.vip_reward_type === 0) {
    formData.vip_reward_threshold = 0
    formData.vip_reward_level = 0
  }
}

function onVipRewardLevelChange(e) {
  formData.vip_reward_level = parseInt(e.detail.value)
}

function onStartDateChange(e) {
  formData.start_date = e.detail.value
}

function onEndDateChange(e) {
  formData.end_date = e.detail.value
}

function onStatusChange(e) {
  formData.status = parseInt(e.detail.value)
}

// 富文本编辑器相关
const editorReady = ref(false)

function onEditorReady() {
  uni.createSelectorQuery().select('#promotion-editor').context((res) => {
    editorCtx.value = res.context
    
    // 延迟标记为准备完成，确保 Quill 完全初始化
    setTimeout(() => {
      editorReady.value = true
      
      // 如果有已存在的内容，设置到编辑器中
      if (formData.content && editorCtx.value) {
        try {
          editorCtx.value.setContents({
            html: formData.content
          })
        } catch (err) {
          console.error('设置编辑器内容失败:', err)
        }
      }
    }, 300)
  }).exec()
}

function onEditorInput(e) {
  // 富文本内容会自动保存为HTML格式
  formData.content = e.detail.html
}

// 检查编辑器是否已初始化
function checkEditorReady() {
  if (!editorCtx.value || !editorReady.value) {
    uni.showToast({ 
      title: '编辑器初始化中，请稍候', 
      icon: 'none',
      duration: 1500
    })
    return false
  }
  return true
}

// 撤销/重做
function editorUndo() {
  if (!checkEditorReady()) return
  try {
    editorCtx.value.undo()
  } catch (err) {
    console.error('撤销失败:', err)
  }
}

function editorRedo() {
  if (!checkEditorReady()) return
  try {
    editorCtx.value.redo()
  } catch (err) {
    console.error('重做失败:', err)
  }
}

// 安全执行编辑器格式化操作
function safeFormat(formatType, value = null) {
  if (!checkEditorReady()) return
  
  try {
    // 先获取焦点，确保编辑器有选区
    // editorCtx.value.blur()
    // setTimeout(() => {
    //   editorCtx.value.getContents()
    // }, 50)
    
    if (value !== null) {
      editorCtx.value.format(formatType, value)
    } else {
      editorCtx.value.format(formatType)
    }
  } catch (err) {
    console.error(`格式化 ${formatType} 失败:`, err)
    uni.showToast({ 
      title: '操作失败，请先在编辑器中输入或选中文本', 
      icon: 'none',
      duration: 2000
    })
  }
}

// 文本格式
function formatBold() {
  safeFormat('bold')
}

function formatItalic() {
  safeFormat('italic')
}

function formatUnderline() {
  safeFormat('underline')
}

function formatStrike() {
  safeFormat('strike')
}

// 标题
function formatHeader(level) {
  safeFormat('header', level)
}

// 列表
function formatList(type) {
  // type: 'ordered'(有序), 'bullet'(无序), 'check'(任务列表)
  safeFormat('list', type)
}

// 对齐方式
function formatAlign(align) {
  // align: 'left', 'center', 'right', 'justify'
  safeFormat('align', align)
}

// 缩进
function formatIndent(value) {
  // value: '+1' 增加缩进, '-1' 减少缩进
  safeFormat('indent', value)
}

// 插入分割线
function insertDivider() {
  if (!checkEditorReady()) return
  try {
    editorCtx.value.insertDivider()
    uni.showToast({ title: '已插入分割线', icon: 'success', duration: 1000 })
  } catch (err) {
    console.error('插入分割线失败:', err)
    uni.showToast({ title: '操作失败', icon: 'none', duration: 1000 })
  }
}

// 插入图片
function insertImage() {
  if (!checkEditorReady()) return
  
  uni.chooseImage({
    count: 1,
    sizeType: ['compressed'],
    sourceType: ['album', 'camera'],
    success: (res) => {
      const tempFilePath = res.tempFilePaths[0]
      try {
        // 这里应该上传到云存储，为了演示先使用本地路径
        editorCtx.value.insertImage({
          src: tempFilePath,
          width: '100%',
          success: () => {
            uni.showToast({ title: '图片插入成功', icon: 'success', duration: 1000 })
          },
          fail: () => {
            uni.showToast({ title: '图片插入失败', icon: 'none', duration: 1500 })
          }
        })
      } catch (err) {
        console.error('插入图片失败:', err)
        uni.showToast({ title: '插入图片失败', icon: 'none', duration: 1500 })
      }
    },
    fail: () => {
      uni.showToast({ title: '图片选择失败', icon: 'none', duration: 1500 })
    }
  })
}

// 清除格式
function clearFormat() {
  if (!checkEditorReady()) return
  try {
    editorCtx.value.removeFormat()
    uni.showToast({ title: '已清除格式', icon: 'success', duration: 1000 })
  } catch (err) {
    console.error('清除格式失败:', err)
    uni.showToast({ title: '操作失败', icon: 'none', duration: 1000 })
  }
}

// uni-file-picker 图片选择相关（不自动上传）
function handleImageSelect(e) {
  // 当 auto-upload 为 false 时，需要手动保存 tempFiles 到 v-model 绑定的变量
  if (e.tempFiles && e.tempFiles.length > 0) {
    imageFileList.value = e.tempFiles
  }
}

function handleImageDelete(e) {
  // 用户删除了选择的图片
  imageFileList.value = []
}

// 上传图片到云存储
async function uploadImageToCloud() {
  if (!imageFileList.value || imageFileList.value.length === 0) {
    return null
  }
  
  try {
    const tempFile = imageFileList.value[0]
    
    // 尝试多种路径获取方式
    const tempFilePath = tempFile.path || tempFile.url || tempFile.tempFilePath || tempFile.tempFilePaths?.[0]
    
    if (!tempFilePath) {
      throw new Error('未找到图片临时路径')
    }
    
    // 使用 uniCloud.uploadFile 上传到云存储
    const uploadResult = await uniCloud.uploadFile({
      filePath: tempFilePath,
      cloudPath: `promotions/${Date.now()}_${Math.random().toString(36).substr(2, 9)}.jpg`,
      cloudPathAsRealPath: false
    })
    
    return uploadResult.fileID
  } catch (err) {
    console.error('图片上传失败:', err)
    throw err
  }
}

function validateStep(step) {
  let isValid = true
  
  if (step === 1) {
  if (!formData.title || formData.title.trim().length === 0) {
      errors.title = '请输入活动标题'
    isValid = false
  } else {
    errors.title = ''
    }
  }
  
  if (step === 2) {
    if (!formData.promotion_category) {
      errors.promotion_category = '请选择促销类别'
    isValid = false
    } else {
      errors.promotion_category = ''
    }
  }
  
  if (step === 3) {
    if (!formData.discount_type) {
      errors.discount_type = '请选择折扣类型'
    isValid = false
  } else {
      errors.discount_type = ''
    }
    
    if (formData.discount_type === 1) {
      const discountValue = parseFloat(formData.discount_value)
      if (isNaN(discountValue) || discountValue <= 0 || discountValue > 1) {
        errors.discount_value = '折扣值应在0-1之间'
        isValid = false
      } else {
        errors.discount_value = ''
      }
    } else if (formData.discount_type === 2 || formData.discount_type === 3) {
      const discountValue = parseFloat(formData.discount_value)
      if (isNaN(discountValue) || discountValue <= 0) {
        errors.discount_value = '请输入有效的金额'
        isValid = false
      } else {
        errors.discount_value = ''
      }
      
      if (formData.discount_type === 3) {
        const minAmount = parseFloat(formData.min_amount)
        if (isNaN(minAmount) || minAmount <= 0) {
          errors.min_amount = '请输入有效的最低消费金额'
          isValid = false
        } else {
          errors.min_amount = ''
        }
      }
    } else if (formData.discount_type === 4) {
      const specialPrice = parseFloat(formData.special_price)
      if (isNaN(specialPrice) || specialPrice <= 0) {
        errors.special_price = '请输入有效的特价金额'
        isValid = false
      } else {
        errors.special_price = ''
      }
    }
  }
  
  if (step === 4) {
    if (formData.vip_reward_type > 0) {
      const threshold = parseFloat(formData.vip_reward_threshold)
      if (isNaN(threshold) || threshold <= 0) {
        errors.vip_reward_threshold = '请输入有效的充值/消费阈值'
    isValid = false
      } else {
        errors.vip_reward_threshold = ''
      }
      
      if (!formData.vip_reward_level || formData.vip_reward_level === 0) {
        errors.vip_reward_level = '请选择VIP等级'
    isValid = false
  } else {
        errors.vip_reward_level = ''
      }
    }
  }
  
  if (step === 5) {
  if (!formData.start_date) {
    errors.start_date = '请选择开始日期'
    isValid = false
  } else {
    errors.start_date = ''
  }
  
  if (!formData.end_date) {
    errors.end_date = '请选择结束日期'
    isValid = false
    } else if (formData.end_date < formData.start_date) {
    errors.end_date = '结束日期不能早于开始日期'
    isValid = false
  } else {
    errors.end_date = ''
    }
  }
  
  return isValid
}

function handlePrevStep() {
  if (currentStep.value > 1) {
    currentStep.value--
  }
}

function handleNextStep() {
  if (!validateStep(currentStep.value)) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  if (currentStep.value < 5) {
    currentStep.value++
  }
}

async function handleSubmit() {
  if (!validateStep(5)) {
    uni.showToast({ title: '请检查表单错误', icon: 'none' })
    return
  }
  
  try {
    uni.showLoading({ title: '保存中...' })
    
    // 第一步：处理图片上传
    let uploadedImageUrl = originalImageUrl.value || formData.image || ''
    
    // 检查是否有新选择的图片（临时文件）
    const hasNewImage = imageFileList.value && 
                        imageFileList.value.length > 0 && 
                        imageFileList.value[0].path && 
                        !imageFileList.value[0].url
    
    if (hasNewImage) {
      try {
        uni.showLoading({ title: '上传图片中...' })
        uploadedImageUrl = await uploadImageToCloud()
        
        if (!uploadedImageUrl) {
          throw new Error('图片上传失败')
        }
        
        uni.showToast({ 
          title: '图片上传成功', 
          icon: 'success',
          duration: 1000
        })
      } catch (uploadErr) {
        uni.hideLoading()
        uni.showToast({ 
          title: '图片上传失败：' + (uploadErr.message || '未知错误'), 
          icon: 'none',
          duration: 3000
        })
        return
      }
    }
    
    // 第二步：准备提交数据
    uni.showLoading({ title: '保存数据中...' })
    
    const submitData = {
      ...formData,
      image: uploadedImageUrl, // 使用上传后的云存储URL
      discount_value: parseFloat(formData.discount_value) || 0,
      min_amount: parseFloat(formData.min_amount) || 0,
      max_discount_amount: formData.max_discount_amount ? parseFloat(formData.max_discount_amount) : null,
      special_price: formData.special_price ? parseFloat(formData.special_price) : null,
      vip_reward_threshold: parseFloat(formData.vip_reward_threshold) || 0,
      priority: parseInt(formData.priority) || 5,
      display_order: parseInt(formData.display_order) || 100
    }
    
    // 第三步：调用云函数更新促销活动
    const result = await dhPromotions.updatePromotion(promotionId.value, submitData)
    
    uni.hideLoading()
    
    if (result.code === 200) {
      uni.showToast({ title: '更新成功', icon: 'success' })
      setTimeout(() => {
        uni.redirectTo({
          url: '/pages/business/hospital_promotions/list'
        })
      }, 1500)
    } else {
      uni.showToast({ title: result.message || '更新失败', icon: 'none' })
    }
  } catch (err) {
    console.error('更新失败:', err)
    uni.hideLoading()
    uni.showToast({ 
      title: err.message || '更新失败', 
      icon: 'none',
      duration: 3000
    })
  }
}

function handleCancel() {
  uni.redirectTo({
    url: '/pages/business/hospital_promotions/list'
  })
}
</script>

<style lang="scss" scoped>
.promotion-edit-container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.page-loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 200rpx 0;
}

.loading-spinner {
  width: 80rpx;
  height: 80rpx;
  border: 6rpx solid #f3f3f3;
  border-top: 6rpx solid #007aff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 30rpx;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

.loading-text {
  font-size: 28rpx;
  color: #666;
}

.page-header {
  padding: 30rpx;
  background-color: #fff;
  border-radius: 10rpx;
  margin-bottom: 20rpx;
  text-align: center;
}

.page-title {
  font-size: 40rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 10rpx;
}

.page-subtitle {
  font-size: 26rpx;
  color: #6b7280;
}

.steps-indicator {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30rpx;
  padding: 0 10rpx;
}

.step-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  flex: 1;
  position: relative;
  
  &::after {
    content: '';
    position: absolute;
    top: 20rpx;
    left: 50%;
    width: 100%;
    height: 2rpx;
    background-color: #e5e7eb;
    z-index: 0;
  }
  
  &:last-child::after {
    display: none;
  }
  
  &.active .step-number {
    background-color: #3b82f6;
    color: white;
  }
  
  &.completed .step-number {
    background-color: #10b981;
    color: white;
  }
  
  &.completed::after {
    background-color: #10b981;
  }
}

.step-number {
  width: 40rpx;
  height: 40rpx;
  border-radius: 50%;
  background-color: #e5e7eb;
  color: #9ca3af;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24rpx;
  font-weight: 600;
  margin-bottom: 10rpx;
  z-index: 1;
}

.step-label {
  font-size: 22rpx;
  color: #6b7280;
  text-align: center;
}

.form-container {
  background-color: #fff;
  border-radius: 10rpx;
  padding: 30rpx;
  min-height: 600rpx;
  position: relative;
  z-index: 1;
}

.form-step {
  animation: fadeIn 0.3s ease;
  position: relative;
  z-index: 2;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20rpx); }
  to { opacity: 1; transform: translateY(0); }
}

.form-section {
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 1px solid #e5e7eb;
  
  &:last-of-type {
    border-bottom: none;
  }
}

.section-title {
  display: block;
  font-size: 32rpx;
  font-weight: 600;
  color: #1f2937;
  margin-bottom: 10rpx;
  padding-left: 15rpx;
  border-left: 5px solid #3b82f6;
}

.section-desc {
  display: block;
  font-size: 24rpx;
  color: #6b7280;
  margin-bottom: 20rpx;
  padding-left: 20rpx;
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  margin-bottom: 15rpx;
  font-weight: 500;
}

.form-label.required::before {
  content: '* ';
  color: #dc3545;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
  line-height: 1.5;
  pointer-events: auto;
  user-select: auto;
  -webkit-user-select: auto;
}

.form-textarea {
  min-height: 150rpx;
  
  &.large {
    min-height: 300rpx;
  }
}

.date-picker {
  width: 100%;
}

.picker-input {
  width: 100%;
  padding: 20rpx;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  background-color: #fff;
  color: #333;
}

.radio-group {
  display: flex;
  flex-wrap: wrap;
  gap: 40rpx;
  
  &.vertical {
    flex-direction: column;
    gap: 20rpx;
  }
}

.radio-label {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.radio-label-block {
  display: flex;
  align-items: flex-start;
  gap: 15rpx;
  padding: 20rpx;
  background-color: #f9fafb;
  border: 2px solid #e5e7eb;
  border-radius: 10rpx;
  transition: all 0.3s;
  
  &:active {
    background-color: #eff6ff;
    border-color: #3b82f6;
  }
}

.radio-content {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.radio-title {
  font-size: 28rpx;
  color: #1f2937;
  font-weight: 600;
  margin-bottom: 8rpx;
}

.radio-desc {
  font-size: 24rpx;
  color: #6b7280;
  line-height: 1.5;
}

.checkbox-group {
  display: flex;
  flex-wrap: wrap;
  gap: 30rpx;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 10rpx;
  font-size: 28rpx;
  color: #333;
}

.form-hint {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #6b7280;
  line-height: 1.5;
}

.error-text {
  display: block;
  margin-top: 10rpx;
  font-size: 24rpx;
  color: #dc3545;
}

.form-actions {
  display: flex;
  gap: 20rpx;
  margin-top: 50rpx;
}

.btn-prev, .btn-next, .btn-submit, .btn-cancel {
  flex: 1;
  padding: 25rpx;
  border-radius: 8rpx;
  font-size: 32rpx;
  border: none;
  cursor: pointer;
  text-align: center;
}

.btn-prev {
  background-color: #6c757d;
  color: #fff;
}

.btn-next {
  background-color: #3b82f6;
  color: #fff;
}

.btn-submit {
  background-color: #10b981;
  color: #fff;
}

.btn-cancel {
  background-color: #e5e7eb;
  color: #6b7280;
}

/* =========================
   H5端专业富文本编辑器样式
   ========================= */
.professional-editor-container {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 4rpx;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.08);
}

.professional-toolbar {
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  padding: 8rpx 12rpx;
}

.toolbar-row {
  display: flex;
  align-items: center;
  gap: 4rpx;
  flex-wrap: wrap;
}

.pro-btn {
  min-width: 60rpx;
  height: 60rpx;
  padding: 0 12rpx;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 4rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  transition: all 0.2s ease;
  
  &:hover {
    background-color: #fafafa;
    border-color: #40a9ff;
    z-index: 1;
  }
  
  &:active {
    background-color: #e6f7ff;
    border-color: #1890ff;
  }
  
  &.danger-btn {
    &:hover {
      background-color: #fff1f0;
      border-color: #ff4d4f;
    }
    
    &:active {
      background-color: #fff1f0;
      border-color: #cf1322;
    }
    
    .pro-icon {
      color: #ff4d4f;
    }
  }
}

.pro-icon {
  font-size: 32rpx;
  font-weight: 600;
  color: #595959;
  line-height: 1;
  
  &.bold {
    font-family: 'Arial Black', 'Microsoft YaHei Bold', sans-serif;
    font-weight: 900;
  }
  
  &.italic {
    font-style: italic;
    font-family: 'Times New Roman', 'KaiTi', serif;
  }
  
  &.underline {
    text-decoration: underline;
    text-decoration-thickness: 2rpx;
  }
  
  &.strike {
    text-decoration: line-through;
    text-decoration-thickness: 2rpx;
  }
}

.pro-divider {
  width: 1px;
  height: 40rpx;
  background-color: #d9d9d9;
  margin: 0 8rpx;
}

.professional-editor-wrapper {
  width: 100%;
  min-height: 500rpx;
  background-color: #fff;
}

.professional-rich-editor {
  width: 100%;
  min-height: 500rpx;
  padding: 20rpx 24rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 1.8;
  color: #262626;
}

/* =========================
   小程序端紧凑富文本编辑器样式（专业灰色风格）
   ========================= */
.compact-editor-container {
  width: 100%;
  border: 1px solid #e0e0e0;
  border-radius: 8rpx;
  overflow: hidden;
  background-color: #fff;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.06);
}

.compact-toolbar {
  display: flex;
  align-items: center;
  justify-content: space-around;
  padding: 10rpx 8rpx;
  background-color: #f5f5f5;
  border-bottom: 1px solid #e0e0e0;
  gap: 6rpx;
}

.compact-btn {
  flex: 1;
  max-width: 80rpx;
  height: 65rpx;
  background-color: #fff;
  border: 1px solid #d9d9d9;
  border-radius: 6rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  
  &:active {
    background-color: #e6f7ff;
    border-color: #1890ff;
    transform: scale(0.96);
  }
  
  &.danger {
    &:active {
      background-color: #fff1f0;
      border-color: #ff4d4f;
    }
    
    .compact-icon {
      color: #ff4d4f;
    }
  }
}

.compact-icon {
  font-size: 36rpx;
  font-weight: 600;
  color: #595959;
  line-height: 1;
  
  &.bold {
    font-family: 'Arial Black', sans-serif;
    font-weight: 900;
  }
  
  &.italic {
    font-style: italic;
    font-family: 'Times New Roman', serif;
  }
  
  &.underline {
    text-decoration: underline;
    text-decoration-thickness: 2rpx;
  }
  
  &.strike {
    text-decoration: line-through;
    text-decoration-thickness: 2rpx;
  }
}

.compact-editor-wrapper {
  width: 100%;
  min-height: 400rpx;
  background-color: #fff;
}

.compact-rich-editor {
  width: 100%;
  min-height: 400rpx;
  padding: 25rpx;
  box-sizing: border-box;
  font-size: 28rpx;
  line-height: 1.6;
  color: #262626;
}

/* 商品/服务选择按钮 */
.select-btn {
  width: 100%;
  padding: 30rpx;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  border-radius: 12rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 10rpx;
  box-shadow: 0 4rpx 12rpx rgba(102, 126, 234, 0.3);
  transition: all 0.3s;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 8rpx rgba(102, 126, 234, 0.2);
  }
}

.select-btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #fff;
}

.select-btn-icon {
  font-size: 36rpx;
  font-weight: 600;
  color: #fff;
}

/* 已选择的商品/服务列表 */
.selected-items-list {
  margin-top: 20rpx;
  display: flex;
  flex-direction: column;
  gap: 15rpx;
}

.selected-item-card {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8fafc;
  border: 1px solid #e2e8f0;
  border-radius: 10rpx;
  transition: all 0.3s;
  
  &:active {
    background-color: #f1f5f9;
  }
}

.item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.item-name {
  font-size: 28rpx;
  font-weight: 600;
  color: #1e293b;
}

.item-price {
  font-size: 26rpx;
  color: #10b981;
  font-weight: 600;
}

.remove-btn {
  width: 50rpx;
  height: 50rpx;
  background-color: #ef4444;
  color: #fff;
  border: none;
  border-radius: 50%;
  font-size: 36rpx;
  font-weight: 600;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  
  &:active {
    background-color: #dc2626;
  }
}

/* 弹窗选择器 */
.picker-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 9999;
  padding: 40rpx;
}

.picker-content {
  width: 100%;
  max-width: 700rpx;
  max-height: 90vh;
  background-color: #fff;
  border-radius: 20rpx;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  box-shadow: 0 20rpx 60rpx rgba(0, 0, 0, 0.3);
}

.picker-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1px solid #e5e7eb;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.picker-title {
  font-size: 36rpx;
  font-weight: 700;
  color: #fff;
}

.picker-close {
  width: 50rpx;
  height: 50rpx;
  border-radius: 50%;
  background-color: rgba(255, 255, 255, 0.2);
  color: #fff;
  border: none;
  font-size: 40rpx;
  line-height: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  
  &:active {
    background-color: rgba(255, 255, 255, 0.3);
  }
}

.picker-search {
  padding: 20rpx 30rpx;
  border-bottom: 1px solid #e5e7eb;
  background-color: #f9fafb;
}

.search-input {
  width: 100%;
  padding: 20rpx 25rpx;
  background-color: #fff;
  border: 1px solid #d1d5db;
  border-radius: 10rpx;
  font-size: 28rpx;
  box-sizing: border-box;
  
  &:focus {
    border-color: #667eea;
  }
}

.picker-tabs {
  display: flex;
  padding: 20rpx 30rpx;
  gap: 20rpx;
  background-color: #f9fafb;
  border-bottom: 1px solid #e5e7eb;
}

.tab-btn {
  flex: 1;
  padding: 18rpx;
  background-color: #fff;
  border: 2px solid #e5e7eb;
  border-radius: 10rpx;
  font-size: 28rpx;
  color: #6b7280;
  font-weight: 600;
  transition: all 0.3s;
  
  &.active {
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border-color: #667eea;
    color: #fff;
  }
  
  &:active {
    transform: scale(0.96);
  }
}

.picker-list {
  flex: 1;
  overflow-y: auto;
  padding: 20rpx 30rpx;
}

.empty-tip {
  padding: 100rpx 0;
  text-align: center;
  color: #9ca3af;
  font-size: 28rpx;
}

.picker-item {
  display: flex;
  align-items: flex-start;
  gap: 20rpx;
  padding: 25rpx;
  margin-bottom: 15rpx;
  background-color: #f9fafb;
  border: 2px solid #e5e7eb;
  border-radius: 12rpx;
  transition: all 0.3s;
  
  &:active {
    background-color: #f3f4f6;
    border-color: #667eea;
  }
}

.picker-item-info {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 10rpx;
}

.picker-item-name {
  font-size: 30rpx;
  font-weight: 600;
  color: #1f2937;
}

.picker-item-desc {
  font-size: 24rpx;
  color: #6b7280;
  line-height: 1.5;
}

.picker-item-price {
  font-size: 28rpx;
  color: #10b981;
  font-weight: 700;
}

.picker-footer {
  display: flex;
  gap: 20rpx;
  padding: 25rpx 30rpx;
  border-top: 1px solid #e5e7eb;
  background-color: #fff;
}

.picker-btn-cancel, .picker-btn-confirm {
  flex: 1;
  padding: 25rpx;
  border-radius: 12rpx;
  font-size: 32rpx;
  font-weight: 600;
  border: none;
}

.picker-btn-cancel {
  background-color: #e5e7eb;
  color: #6b7280;
  
  &:active {
    background-color: #d1d5db;
  }
}

.picker-btn-confirm {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: #fff;
  
  &:active {
    opacity: 0.9;
  }
}
</style>

